package br.usp.pcs.basys2.engine;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

import br.usp.pcs.basys2.SimulationInput;
import br.usp.pcs.basys2.SimulationInputDao;

import com.thoughtworks.xstream.XStream;

public class Simulation {

	/**
	 * @param args
	 * @throws FileNotFoundException
	 */
	public static void main(String[] args) throws FileNotFoundException {
		Engine engine = Engine.getInstance();
		String inputFileName = args.length > 0 ? args[0] : "input.xml";
		String inputName = inputFileName.split("[.]")[0];
		String outputFileName = args.length > 1 ? args[1] : inputName
				+ "-result.xml";
		String outputImageFileName = args.length > 2 ? args[2] : inputName
				+ "-gantt_chart.png";
		try {
			SimulationInputDao dao = new SimulationInputDao();
			InputStream input = new FileInputStream(inputFileName);
			SimulationInput simulationInput = dao.load(input);
			engine.setSystem(simulationInput.getSystem());
			engine.load(simulationInput.getJobs());
			engine.run();
			engine.getOutputDataGenerator().exportToPng(outputImageFileName, inputFileName);
		} catch (RuntimeException e) {
			System.err.println("Done with errors!");
			e.printStackTrace();
		} finally {
			SimulationOutput output = engine.getOutput();
			XStream stream = new XStream();
			stream
					.toXML(output, new FileOutputStream(
							new File(outputFileName)));

		}
	}

}
